import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'
import routes from './router';
import { DirectionType, AppModule } from '@/store/modules/app'

Vue.use(Router)
// 路由配置
let RouterConfig: any = {
    mode: 'history',
    base: process.env.BASE_URL,
    routes,
    scrollBehavior() {
        return {
            x: 0,
            y: 0
        }
    },
};
const router = new Router(RouterConfig);
const history = window.sessionStorage;
let count:any = history.getItem('count') || 1;
let historyCount:any = count * 1;

router.beforeEach((to: any, from: any, next: any) => {
    // 根据路由的meta中name属性动态的激活底部tabbar
    if (to.meta.name) {
        AppModule.ToggleTabbar(to.meta.name);
    } else {
        AppModule.ToggleTabbar(0);
    }

    const toIndex = history.getItem(to.path);
    const fromIndex = history.getItem(from.path);

    if (toIndex) {
        if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
            // store.commit('TOGGLE_DIRECTION', {
            //     direction: 'forward'
            // })
            AppModule.ToggleDirection(DirectionType.forward);
        } else {
            // store.commit('TOGGLE_DIRECTION', {
            //     direction: 'reverse'
            // })
            AppModule.ToggleDirection(DirectionType.forward);
        }
    } else {
        ++historyCount;
        history.setItem('count', historyCount);
        to.path !== '/' && history.setItem(to.path, historyCount);
        // store.commit('TOGGLE_DIRECTION', {
        //     direction: 'forward'
        // })
        AppModule.ToggleDirection(DirectionType.reverse);
    }
    if (/\/http/.test(to.path)) {
        let url = to.path.split('http')[1];
        window.location.href = `http${url}`
    } else {
        next()
    }
})

router.afterEach((to: any, form) => {
    // 在路由的meta中定义hideArr 判断是否需要显示返回按钮
    if (to.meta.needBack) {
        AppModule.ToggleBack(true)
    }else{
        AppModule.ToggleBack(false)
    }
    // if(to.meta.hideTools) {
    //     store.dispatch('ToggleTools', {
    //         needTools: false
    //     })
    // }else{
    //     store.dispatch('ToggleTools', {
    //         needTools: true
    //     })
    // }
    // 根据路由的name动态显示顶部标题
    AppModule.ToggleTitle(to.meta.title)
    window.scrollTo(0, 0)
})



export default router
